//++
//
// Copyright (c) Microsoft Corporation.  All rights reserved.
//
// Module Name:
//
//    RulesLoader.cs
//
// Abstract:
//    
//    Implements IRulesLoader for loading/saving notification rules.
//
//--

using System;
using System.Diagnostics;

namespace Microsoft.EnhancedReminders.OutlookAddIn
{
    /// <summary>
    /// Implementation of IRulesLoader to load and save rules using the Outlook storage mechanism.
    /// </summary>
    public sealed class RulesLoader : IRulesLoader
    {
        /// <summary>
        /// ctor.
        /// </summary>
        public RulesLoader()
        {
        }

        /// <summary>
        /// Load rules from Outlook storage.
        /// </summary>
        /// <param name="rules">An empty rules collection to be populated with the stored rules.</param>
        public void Load(NotificationRules rules)
        {
            Debug.Assert(rules != null, "rules");
            Debug.Assert(rules.Count == 0, "rules.Count");
            Debug.Assert(Globals.ThisAddIn.Application != null, "Globals.ThisAddIn.Application");

            OutlookApplication application = new OutlookApplication(Globals.ThisAddIn.Application);

            ReminderOutlookUtils.LoadRules(application, ref rules);

            VerifyRules(rules);
        }

        /// <summary>
        /// Verify the correctness of a set of rules.
        /// </summary>
        /// <param name="rules">The rules to verify.</param>
        [Conditional("DEBUG")]
        private static void VerifyRules(NotificationRules rules)
        {
            Debug.Assert(rules != null, "rules");

            foreach (NotificationRuleItem rule in rules)
            {
                Debug.Assert(NotificationConditionHelper.VerifyConditions(rule), "Rule has invalid conditions.");
            }
        }

        /// <summary>
        /// Save the rules to Outlook storage.
        /// </summary>
        /// <param name="rules">The rules to be saved.</param>
        public void Save(NotificationRules rules)
        {
            Debug.Assert(rules != null, "rules");

            OutlookApplication application = new OutlookApplication(Globals.ThisAddIn.Application);

            // Workaround for WPF item non-serializable.           
            NotificationRules saveRules = new NotificationRules();
            foreach (NotificationRuleItem rule in rules)
            {
                saveRules.Add(rule);
            }

            ReminderOutlookUtils.SaveRules(saveRules, application);
        }
    }
}
